<template>

  <el-dialog v-model="dialogMultiple" :title="dialogTitle" width="90%" @close="dialogPdfClose">
    <div class="flexCustom">
      <div v-for="(item,index) in props.dialogArray" :key="index">
        <div class="margin-bottom text-h2">{{item.nameNew}}</div>
        <template v-if="item.suffix=='docx'||item.suffix=='doc'">
          <el-link :href="`${item.src}`" :underline="false" target="_blank" class="margin-bottom">
            <el-button>下载</el-button>
          </el-link>
          <div ref="docxRef" class="word-div"></div>
        </template>
        <template v-if="item.suffix=='xls'||item.suffix=='xlsx'">
          <el-link :href="`${item.src}`" :underline="false" target="_blank" class="margin-bottom">
            <el-button>下载</el-button>
          </el-link>
          <div ref="xlsxRef" class="xlsx-div">
            <el-tabs v-model="activeName" type="border-card">
              <el-tab-pane v-for="(opt, i) in excelSheetObj['excelSheet'+index]" :key="i" :label="opt.name" :name="opt.name">
                <div class="table" v-html="opt.html"></div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </template>
        <template v-if="item.suffix=='jpg'||item.suffix=='jpeg'||item.suffix=='png'">
          <el-link :href="`${item.src}`" :underline="false" target="_blank" class="margin-bottom">
            <el-button>下载</el-button>
          </el-link>
          <div class="img-div">
            <el-image :src="fileData.src" :alt="fileData.fileOldName" />
          </div>
        </template>
        <template v-if="item.suffix=='pdf'">
          <el-link :href="`${item.src}`" :underline="false" target="_blank" class="margin-bottom">
            <el-button>下载</el-button>
          </el-link>
          <div class="pdf-div">
            <iframe id="pdfRef" :src="iframeUrlObj['iframeUrl'+index]" frameborder="0" style="width: 100%; height: 99%"></iframe>
          </div>
        </template>
      </div>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
import axios from "axios";
import { defineProps, ref, reactive, computed, nextTick, watch } from "vue";
import { renderAsync } from "docx-preview";
import * as XLSX from "xlsx";

const props = defineProps({
  dialogShowNum: {
    type: Number,
    default: 1,
  },
  dialogArray: {
    type: Array,
    default: [{}, {}, {}],
  },
  dialogTitle: {
    type: String,
    default: "预览",
  },
});
const { proxy } = getCurrentInstance();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const dialogDocxValue: any = ref(false);
let dialogTitle = computed(() => {
  return props.dialogTitle;
});
const fileHtml = ref("");
const excelSheetObj = ref({});

// 预览
/** 传值监听 */
watch(
  () => props.dialogArray,
  (newValue) => {
    if (newValue) {
      let docxIndex = 0;
      let xlsxIndex = 0;
      let imgIndex = 0;
      let pdfIndex = 0;
      newValue.forEach((item, index) => {
        if (item.suffix == "docx" || item.suffix == "doc") {
          viewDocx(item, docxIndex);
          docxIndex++;
        } else if (item.suffix == "xlsx" || item.suffix == "xls") {
          viewXlsx(item, xlsxIndex, index);
          xlsxIndex++;
        } else if (
          item.suffix == "jpg" ||
          item.suffix == "jpeg" ||
          item.suffix == "png"
        ) {
          viewImg(item, index);
          imgIndex++;
        } else if (item.suffix == "pdf") {
          viewPdf(item, index);
          pdfIndex++;
        }
      });
    }
  },
  { immediate: true, deep: true }
);

const docxRef = ref<any>();
// doc 文档预览
const viewDocx = (data: any, index: Number) => {
  docxRef.value = "";

  dialogDocxValue.value = true;
  dialogMultiple.value = true;
  if (data.src) {
    // 已上传的文件
    let srcFile = "";
    if (data.src.indexOf(",")) {
      srcFile = data.src.split(",")[0];
    } else {
      srcFile = data.src;
    }
    axios({
      url: srcFile,
      method: "get",
      responseType: "blob",
    }).then((res) => {
      if (res.status == 200) {
        const content = res.data;
        const blob = new Blob([content]);
        nextTick(() => {
          dialogDocxValue.value = true;
          // dialogTitle = data.fileOldName || data.name;
          renderAsync(blob, proxy.$refs.docxRef[index]).then(
            (reson) => {
              dialogDocxValue.value = true;
              // dialogTitle = data.fileOldName || data.name;
            },
            (err) => {
              dialogDocxValue.value = false;
              proxy.$modal.msg("由于文档是doc旧版本,需要下载预览");
              downloadFile(srcFile);
            }
          );
        });
      }
    });
  } else {
    // 本地文件
    const blob = new Blob([data.raw]);
    nextTick(() => {
      dialogDocxValue.value = true;
      dialogMultiple.value = true;
      renderAsync(blob, docxRef.value);
      // dialogTitle = data.fileOldName || data.name;
    });
  }
};
const dialogXlsxValue: any = ref(false);
const excelSheet: any = ref([]);
const activeName = ref("");
const dialogDocxClose = () => {
  dialogDocxValue.value = false;
  dialogMultiple.value = false;
  docxRef.value = "";
};
const downloadFile = (fileName) => {
  const fileUrl = "/path/to/" + fileName; // 文件的URL地址
  const link = document.createElement("a");
  link.href = fileUrl;
  link.setAttribute("download", fileName);
  link.click();
};
// xlsx 预览
const viewXlsx = (data: any, index: Number, orderNum: Number) => {
  dialogXlsxValue.value = true;
  dialogMultiple.value = true;
  if (data.src) {
    axios({
      url: data.src,
      method: "get",
      responseType: "blob",
    }).then((res) => {
      if (res.status == 200) {
        const content = res.data;
        // const blob = new Blob(content);
        const reader = new FileReader();
        reader.readAsArrayBuffer(content);
        reader.onload = function (loadEvent: any) {
          const arrayBuffer = loadEvent.target["result"];
          const workbook = XLSX.read(new Uint8Array(arrayBuffer), {
            type: "array",
          });
          const list = [];
          const sheetNames = workbook.SheetNames;
          let num = 0;
          activeName.value = data.title
            ? data.title + "_" + (num + 1)
            : sheetNames[0];

          for (const p of sheetNames) {
            num++;
            let html = "";
            try {
              html = XLSX.utils.sheet_to_html(workbook.Sheets[p]);
            } catch (e) {
              html = "";
            }
            const map = {
              name: data.title ? data.title + "_" + num : p,
              html: html,
            };
            list.push(map);
          }
          // data.excelSheet=list;
          excelSheetObj.value["excelSheet" + orderNum] = list;
          // excelSheet.value = list;
          // dialogTitle = data.fileName || data.name;
        };
      }
    });
  } else {
    const blob = new Blob([data.raw]);
    const reader = new FileReader();
    reader.readAsArrayBuffer(blob);
    reader.onload = function (loadEvent: any) {
      const arrayBuffer = loadEvent.target["result"];
      const workbook = XLSX.read(new Uint8Array(arrayBuffer), {
        type: "array",
      });
      const list = [];
      const sheetNames = workbook.SheetNames;
      let num = 0;
      activeName.value = data.title
        ? data.title + "_" + (num + 1)
        : sheetNames[0];
      for (const p of sheetNames) {
        let html = "";
        try {
          html = XLSX.utils.sheet_to_html(workbook.Sheets[p]);
        } catch (e) {
          html = "";
        }
        const map = {
          name: data.title ? data.title + "_" + num : p,
          html: html,
        };
        list.push(map);
      }
      // excelSheet.value = list;
      excelSheetObj.value["excelSheet" + orderNum] = list;
      // dialogTitle = data.fileName || data.name;
    };
  }
};

const dialogXlsxClose = () => {
  dialogXlsxValue.value = false;
  excelSheet.value = "";
  activeName.value = "";
};
const fileData: any = ref({});
const dialogImgValue: any = ref(false);
// 图片预览
const viewImg = (data: any) => {
  if (data.src) {
    // 已上传的图片
    fileData.value = data;
  } else {
    // 本地图片
    const freader = new FileReader();
    freader.readAsDataURL(data.raw);
    freader.onload = (e: any) => {
      fileData.value = {
        src: e.target.result,
        id: new Date(),
        fileName: data.fileOldName || data.name,
      };
    };
  }
  // dialogTitle = data.fileOldName || data.name;
  dialogImgValue.value = true;
  dialogMultiple.value = true;
};
const dialogImgClose = () => {
  dialogImgValue.value = false;
};

const dialogMultiple: any = ref(false);
const dialogPdfValue: any = ref(false);
const iframeUrl: any = ref("");
const iframeUrlObj: any = ref({});
const pdfRef = ref<any>();
const viewPdf = (data: any, index: Number) => {
  if (data.src) {
    axios({
      url: data.src,
      method: "get",
      responseType: "blob",
    }).then((res) => {
      if (res.status == 200) {
        // 把文件流转化为url
        iframeUrl.value = URL.createObjectURL(res.data);
        iframeUrlObj.value["iframeUrl" + index] = URL.createObjectURL(res.data);
        dialogPdfValue.value = true;
        dialogMultiple.value = true;
      }
    });
  } else {
    iframeUrl.value = URL.createObjectURL(data.raw);
    iframeUrlObj.value["iframeUrl" + index] = URL.createObjectURL(data.raw);
    dialogPdfValue.value = true;
    dialogMultiple.value = true;
  }
};
const dialogPdfClose = () => {
  dialogPdfValue.value = false;
};
defineExpose({
  viewDocx,
  viewXlsx,
  viewImg,
  viewPdf,
});
</script>
<style>
.word-div .docx-wrapper {
  padding: 1px !important;
}
.word-div .docx-wrapper .docx {
  width: 100% !important;
  padding: 10px !important;
}
</style>
<style scoped lang="scss">
.word-div {
  height: calc(70vh);
  overflow: auto;
}

.xlsx-div {
  height: calc(70vh);
  overflow: auto;
}
.img-div {
  height: calc(70vh);
  overflow: auto;
  img {
    width: 100%;
    height: 100%;
  }
}
.pdf-div {
  height: calc(70vh);
  overflow: auto;
}
</style>
<style lang="scss">
.xlsx-div {
  .table-html-wrap table {
    border-right: 1px solid #fff;
    border-bottom: 1px solid #e8eaec;
    border-collapse: collapse;
    // margin: auto;
  }

  .table-html-wrap table td {
    border-left: 1px solid #e8eaec;
    border-top: 1px solid #e8eaec;
    white-space: wrap;
    text-align: left;
    min-width: 100px;
    padding: 4px;
  }

  table {
    border-top: 1px solid #ebeef5;
    border-left: 1px solid #ebeef5;
    width: 100%;
    // overflow: auto;

    tr {
      height: 44px;
    }

    td {
      min-width: 200px;
      max-width: 400px;
      padding: 4px 8px;
      border-right: 1px solid #ebeef5;
      border-bottom: 1px solid #ebeef5;
    }
  }

  .el-tabs--border-card > .el-tabs__content {
    overflow-x: auto;
  }
}

.flexCustom {
  display: flex;
  height: 70vh;
  overflow-y: hidden;
}
.flexCustom > div {
  flex: 1;
  height: 70vh;
  overflow: hidden;
  margin-right: 15px;
}
.margin-bottom {
  margin-bottom: 10px;
}
.text-h2 {
  font-size: 16px;
  color: #333;
}
</style>

